document.addEventListener('DOMContentLoaded', () => {
    const todoList = document.getElementById('todo-list');
    const todoInput = document.getElementById('todo-input');
    const addButton = document.getElementById('add-btn');
    const delAllButton = document.getElementById('del-all-btn');

    // 载入当前用户的待办事项
    function loadTodos() {
        fetch('/todos', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
        .then(response => response.json())
        .then(data => {
            todoList.innerHTML = '';
            data.todos.forEach(todo => {
                const listItem = createTodoElement(todo);
                todoList.appendChild(listItem);
            });
        })
        .catch(err => console.error('加载待办事项失败:', err));
    }

    // 创建待办事项元素
    function createTodoElement(todo) {
        const li = document.createElement('li');
        li.setAttribute('data-id', todo.id);
        
        const textSpan = document.createElement('span');
        textSpan.textContent = todo.content;
        textSpan.classList.add('todo-text');

        const editButton = document.createElement('button');
        editButton.textContent = '✏️';
        editButton.classList.add('edit-btn');
        editButton.addEventListener('click', () => editTodoStart(todo.id, textSpan));

        const deleteButton = document.createElement('button');
        deleteButton.textContent = '🗑️';
        deleteButton.classList.add('delete-btn');
        deleteButton.addEventListener('click', () => deleteTodo(todo.id));

        li.appendChild(textSpan);
        li.appendChild(editButton);
        li.appendChild(deleteButton);

        return li;
    }

    // 添加新的待办事项
    addButton.addEventListener('click', () => {
        const content = todoInput.value.trim();
        if (content) {
            fetch('/todos', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({ content })
            })
            .then(response => response.json())
            .then(data => {
                const newTodo = createTodoElement(data.todo);
                todoList.appendChild(newTodo);
                todoInput.value = '';
            })
            .catch(err => console.error('添加待办事项失败:', err));
        }
    });

    // 删除待办事项
    function deleteTodo(id) {
        fetch(`/todos/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
        .then(() => {
            const item = document.querySelector(`li[data-id="${id}"]`);
            if (item) item.remove();
        })
        .catch(err => console.error('删除待办事项失败:', err));
    }

    // 开始编辑待办事项
    function editTodoStart(id, textSpan) {
        const input = document.createElement('input');
        input.type = 'text';
        input.value = textSpan.textContent;
        textSpan.replaceWith(input);
        
        const saveButton = document.createElement('button');
        saveButton.textContent = 'save';
        saveButton.addEventListener('click', () => editTodoSave(id, input, textSpan));
        input.after(saveButton);
    }

    // 保存编辑的待办事项
    function editTodoSave(id, input, textSpan) {
        const content = input.value.trim();
        if (content) {
            fetch(`/todos/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({ content })
            })
            .then(() => {
                textSpan.textContent = content;
                input.replaceWith(textSpan);
                input.nextElementSibling.remove(); // 删除保存按钮
            })
            .catch(err => console.error('编辑待办事项失败:', err));
        }
    }

    // 删除所有待办事项
    delAllButton.addEventListener('click', () => {
        fetch('/todos', {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
        .then(() => {
            todoList.innerHTML = '';
        })
        .catch(err => console.error('删除所有待办事项失败:', err));
    });

    // 页面载入时加载待办事项
    loadTodos();
});
